package info.thereisonlywe.onenesspathfinder.ui;

import info.thereisonlywe.core.project.ProjectConstants;
import info.thereisonlywe.core.project.ProjectLocalization;
import info.thereisonlywe.core.toolkit.GUIToolkit;
import info.thereisonlywe.quran.QuranicVerse;
import info.thereisonlywe.quran.bookmark.QuranicBookmarkList;
import info.thereisonlywe.quran.search.QuranicSearchResult;
import info.thereisonlywe.quran.search.ui.QuranQueryField;

import java.awt.Color;
import java.awt.Cursor;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ComponentEvent;
import java.awt.event.ComponentListener;
import java.awt.event.FocusAdapter;
import java.awt.event.FocusEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;

import javax.swing.JMenuItem;
import javax.swing.JPopupMenu;
import javax.swing.KeyStroke;
import javax.swing.ToolTipManager;

public class SearchPanel extends QuranQueryField {

	private final JPopupMenu popupMenu_Results = new JPopupMenu();

	private final JPopupMenu popupMenu_Input = new JPopupMenu();

	public SearchPanel()
	{
		super();
		textField.setPreferredSize(new Dimension(100, 30));
		// textField.setFont(FontLibrary.get(FontLibrary.CODE2000, 14));
		table.setSelectionBackground(Color.LIGHT_GRAY);
		table.setSelectionForeground(Color.black);
		setCursor(new Cursor(Cursor.DEFAULT_CURSOR));
		ToolTipManager.sharedInstance().unregisterComponent(table);
		// table.setFont(FontLibrary.get(FontLibrary.CODE2000, 14));
		initPopupItems();
		initListeners();
	}

	public JPopupMenu getPopupMenuResults()
	{
		return popupMenu_Results;
	}

	public JPopupMenu getPopupMenuInput()
	{
		return popupMenu_Input;
	}

	protected void addText(String s)
	{
		textField.setText(textField.getText() + s);
	}

	public QuranicVerse[] getSelectedVerses()
	{
		int rows[] = table.getSelectedRows();
		QuranicVerse[] results = new QuranicVerse[rows.length];
		for (int i = 0; i < results.length; i++)
		{
			results[i] = ((QuranicSearchResult) getResults().get(rows[i]))
					.getVerse();
		}
		return results;
	}

	private void initListeners()
	{

		addFocusListener(new FocusAdapter()
		{

			@Override
			public void focusGained(FocusEvent e)
			{
				if (getResultCount() <= 0) textField.requestFocus();
			}
		});

		addComponentListener(new ComponentListener()
		{

			@Override
			public void componentShown(ComponentEvent e)
			{
				textField.requestFocus();
			}

			@Override
			public void componentResized(ComponentEvent e)
			{

			}

			@Override
			public void componentMoved(ComponentEvent e)
			{

			}

			@Override
			public void componentHidden(ComponentEvent e)
			{

			}
		});

		// textField.addFocusListener(new FocusAdapter()
		// {
		//
		// @Override
		// public void focusGained(FocusEvent e)
		// {
		// MainFrame.getSplitPane().getControlPanel().getMenuPane()
		// .getConfigurationPane().getSearchConfigurationPanel()
		// .applySearchOptions();
		// textField.requestFocus();
		// }
		// });

		textField.addMouseListener(new MouseAdapter()
		{
			@Override
			public void mousePressed(MouseEvent e)
			{
				if (e.isPopupTrigger())
				{
					refreshInputPopup();
					popupMenu_Input.show(e.getComponent(), e.getX(), e.getY());
				}
			}

			@Override
			public void mouseReleased(MouseEvent e)
			{
				if (e.isPopupTrigger())
				{
					refreshInputPopup();
					popupMenu_Input.show(e.getComponent(), e.getX(), e.getY());
				}
			}
		});

		table.addMouseListener(new MouseAdapter()
		{
			@Override
			public void mouseClicked(MouseEvent e)
			{
				if (e.getClickCount() == 2)
				{
					int indices[] = getSelectedRows();
					if (indices.length == 1 && indices[0] >= 0)
					{
						UIDelegate
								.seekToVerse(((QuranicSearchResult) getResult(indices[0]))
										.getVerse());
					}
				}
			}

			@Override
			public void mousePressed(MouseEvent e)
			{
				if (e.isPopupTrigger())
				{
					refreshResultsPopup();
					popupMenu_Results.show(e.getComponent(), e.getX(), e.getY());
				}
			}

			@Override
			public void mouseReleased(MouseEvent e)
			{
				if (e.isPopupTrigger())
				{
					refreshResultsPopup();
					popupMenu_Results.show(e.getComponent(), e.getX(), e.getY());
				}
			}
		});
	}

	private void refreshResultsPopup()
	{
		if (getResultCount() > 0)
		{
			popupMenu_Results.getComponent(3).setEnabled(true);
			if (getSelectedRows().length > 0)
			{
				popupMenu_Results.getComponent(0).setEnabled(true);
				popupMenu_Results.getComponent(1).setEnabled(true);
			}
			else
			{
				popupMenu_Results.getComponent(0).setEnabled(false);
				popupMenu_Results.getComponent(1).setEnabled(false);
			}

		}
		else
		{
			popupMenu_Results.getComponent(0).setEnabled(false);
			popupMenu_Results.getComponent(1).setEnabled(false);
			popupMenu_Results.getComponent(3).setEnabled(false);
		}

	}

	private void initPopupItems()
	{
		JMenuItem item = new JMenuItem(ProjectLocalization.getString(
				ProjectConstants.ONENESS_PATHFINDER_PROJECT, "AddToBookmarks"));
		item.setMargin(UIConstants.MARGIN);
		item.addActionListener(new ActionListener()
		{
			@Override
			public void actionPerformed(ActionEvent e)
			{
				UIDelegate.BookmarkPaneHook.getBookmarkList().addBookmarks(
						getSelectedVerses(), getQuery());
				UIDelegate.BookmarkPaneHook.refresh();
			}
		});
		popupMenu_Results.add(item);

		item = new JMenuItem(ProjectLocalization.getString(
				ProjectConstants.CORE_PROJECT, "Save"));
		item.setMargin(UIConstants.MARGIN);
		item.addActionListener(new ActionListener()
		{
			@Override
			public void actionPerformed(ActionEvent e)
			{
				QuranicBookmarkList qbl = new QuranicBookmarkList();
				qbl.addBookmarks(getSelectedVerses(), getQuery());
				SaveBookmarksDialog.showDialog(qbl.getBookmarks());
				qbl = null;

			}
		});
		popupMenu_Results.add(item);

		popupMenu_Results.addSeparator();
		item = new JMenuItem(ProjectLocalization.getString(
				ProjectConstants.CORE_PROJECT, "SelectAll"));
		item.setMargin(UIConstants.MARGIN);
		item.setAccelerator(KeyStroke.getKeyStroke("ctrl A"));
		item.addActionListener(new ActionListener()
		{
			@Override
			public void actionPerformed(ActionEvent e)
			{
				setSelectedRows(0, getResultCount() - 1);
			}
		});
		popupMenu_Results.add(item);
		// item = new
		// JMenuItem(ProjectLocalization.getString(ProjectConstants.ONENESS_PATHFINDER_PROJECT,
		// "Print"));
		// item.setMargin(OnenessPathfinderGUI.MARGIN);
		// item.addActionListener(new ActionListener() {
		// @Override
		// public void actionPerformed(ActionEvent e) {
		// if (getResultCount()<=0){
		// OnenessPathfinderGUI.openDialog = true;
		// JOptionPane.showOptionDialog(null,
		// ProjectLocalization.getString(ProjectConstants.ONENESS_PATHFINDER_PROJECT,
		// "List.Empty"), "Oneness Pathfinder",
		// JOptionPane.DEFAULT_OPTION,
		// JOptionPane.ERROR_MESSAGE, null, null, null);
		// OnenessPathfinderGUI.openDialog = false;
		// }
		// else {
		// StringBuilder sb = new StringBuilder();
		// QuranicBookmark list[] = getSelectedActiveListedVerses();
		// for (int i = 0; i < list.length; i++)
		// {
		// int index = listedVerses.getOrder
		// ((list[i].getPosition()));
		// sb.append(getResult(index).getValue());
		// if (i+1 < list.length)
		// sb.append("\n");
		// }
		// PlainDocument doc = new PlainDocument();
		// try {
		// doc.insertString(0, sb.toString(), QuranBrowser.getAttributeSet());
		// DocumentRenderer t = new DocumentRenderer();
		// t.print(doc);
		// } catch (BadLocationException ex) {
		// }
		// }
		// }
		// });
		// popupMenu.add(item);

		item = new JMenuItem(ProjectLocalization.getString(
				ProjectConstants.CORE_PROJECT, "Paste"));
		item.setMargin(UIConstants.MARGIN);
		item.setAccelerator(KeyStroke.getKeyStroke("ctrl V"));
		item.addActionListener(new ActionListener()
		{
			@Override
			public void actionPerformed(ActionEvent e)
			{
				String s = GUIToolkit.getClipboardContents();
				if (s != null && s.length() > 0)
				{
					addText(s);
				}
				refresh();
			}
		});
		popupMenu_Input.add(item);
		popupMenu_Input.addSeparator();

		item = new JMenuItem(ProjectLocalization.getString(
				ProjectConstants.CORE_PROJECT, "SelectAll"));
		item.setMargin(UIConstants.MARGIN);
		item.setAccelerator(KeyStroke.getKeyStroke("ctrl A"));
		item.addActionListener(new ActionListener()
		{
			@Override
			public void actionPerformed(ActionEvent e)
			{
				textField.selectAll();
			}
		});
		popupMenu_Input.add(item);
	}

	private void refreshInputPopup()
	{
		String s = GUIToolkit.getClipboardContents();
		if (s != null && s.length() > 0)
		{
			popupMenu_Input.getComponent(0).setEnabled(true);
		}
		else popupMenu_Input.getComponent(0).setEnabled(false);
		if (textField.getText() != null && !textField.getText().isEmpty()) popupMenu_Input
				.getComponent(2).setEnabled(true);
		else popupMenu_Input.getComponent(2).setEnabled(false);
	}

	public void deleteLast()
	{
		String s = textField.getText();
		if (s != null && s.length() > 0)
			textField.setText(new String(s.substring(0, s.length() - 1)));
	}

}
